Flutter / UI Elements / PageView
PageView
-
Usage
The PageView widget in Flutter is used to create a scrollable list of pages that users can swipe through horizontally. It's commonly used to create wizards, image galleries, or any kind of horizontal swiping interface.
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'PageView Tutorial', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'PageView Tutorial'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State { PageController _pageController = PageController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: PageView( controller: _pageController, children: [ colouredContainer(Colors.red, 'Red'), colouredContainer(Colors.yellow, 'Yellow'), colouredContainer(Colors.green, 'Green'), ], ), ); } Widget colouredContainer(Color color, String colorName) { return Container( decoration: BoxDecoration( color: color, ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( colorName, style: TextStyle( color: Colors.white, fontSize: 32.0, ), ), ElevatedButton( onPressed: () { if (_pageController.hasClients) { _pageController.nextPage( duration: Duration(seconds: 1), curve: Curves.easeIn, ); } }, child: Text('Next'), ), ElevatedButton( onPressed: () { if (_pageController.hasClients) { _pageController.previousPage( duration: Duration(seconds: 1), curve: Curves.easeIn, ); } }, child: Text('Previous'), ) ], ), ), ); } } 2. Different methods
# 1. PageView PageView( children: [ Container( color: Colors.red, ), Container( color: Colors.blue, ), Container( color: Colors.green, ), ], ); # 2. PageView.builder PageView.builder( itemBuilder: (context, index){ return Center( child: Text('$index'), ); }, itemCount: 5, ); # 3. PageView.custom PageView.custom( childrenDelegate: SliverChildListDelegate( [ const Text('1'), const Text('2'), const Text('3'), ], ), );